package com.byq.mm.abstractx.cluster.server.access;
import com.byq.mm.abstractx.cluster.server.ServerIdentifier;
import com.byq.mm.abstractx.cluster.server.SmartServer;
import com.byq.mm.abstractx.engine.CoreEnvironment;
import com.byq.mm.abstractx.protocol.Interaction;



public class ServerAccessController implements SmartServer {
	SmartServer proxy;
	Boolean permitted = true;
	CoreEnvironment env;
	public ServerAccessController(CoreEnvironment e, SmartServer proxy) {
		super();
		this.proxy = proxy;
		this.env = e;

	}
	void loadOrSave(){
		if(env.getLiteStore().existPermission(getId()))
			permitted = env.getLiteStore().findPermission(getId());
			else  {
				permitted = false;
				env.getLiteStore().savePermission(getId(), permitted);
			}
	}
	public boolean isPermitted() {
		if(permitted == null)
			loadOrSave();
		return permitted;
	}

	public void togglePermission() {
		permitted = !isPermitted();
		env.getLiteStore().updatePermission(getId(), permitted);
	}

	public void setPermitted(boolean p) {
		this.permitted = p;
		env.getLiteStore().updatePermission(getId(), permitted);
	}
	@Override
	public boolean onCommand(Interaction i, String transport) {
		if(!isPermitted()){
			
			return false;
		}
		return proxy.onCommand(i, transport);

	}

	public void setProxy(SmartServer proxy) {
		this.proxy = proxy;
	}

	@Override
	public ServerIdentifier getId() {
		// TODO Auto-generated method stub
		return proxy.getId();
	}

}
